package com.baitiaojun.tenant.interceptor;

import com.baitiaojun.common.constants.Constants;
import com.baitiaojun.common.enums.impl.ServiceExpEnums;
import com.baitiaojun.common.enums.impl.TenantStatusEnums;
import com.baitiaojun.common.exception.ServiceException;
import com.baitiaojun.common.utils.date.DateTimeUtils;
import com.baitiaojun.common.utils.string.StringUtils;
import com.baitiaojun.datasource.core.datasource.DataSourceHolder;
import com.baitiaojun.datasource.core.datasource.DynamicRoutingDataSource;
import com.baitiaojun.tenant.dto.MasterTenantDTO;
import com.baitiaojun.tenant.service.MasterTenantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class DataSourceInterceptor implements HandlerInterceptor {

    @Autowired
    private MasterTenantService masterTenantService;

    @Autowired
    private DynamicRoutingDataSource dataSource;


    /**
     * 执行方法前执行
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("&&&&&&&&&&&&&&&& 租户拦截, 执行数据源初始化 &&&&&&&&&&&&&&&&");
        String tenant = request.getHeader(Constants.LOGIN_TENANT_KEY);
        if (StringUtils.isEmpty(tenant)) {
            throw new ServiceException(ServiceExpEnums.EXP_DELETION_TENANT);
        }
        if (!dataSource.containDataSources(tenant)) {
            MasterTenantDTO masterTenantDTO = masterTenantService.queryTenant(tenant);
            if (masterTenantDTO == null) {
                throw new ServiceException(ServiceExpEnums.EXP_DISABLE_TENANT);
            }
            if (TenantStatusEnums.DISABLE.getName().equals(masterTenantDTO.getStatus())) {
                throw new ServiceException(ServiceExpEnums.EXP_DISABLE_TENANT);
            }
            Date expirationDate = masterTenantDTO.getExpirationDate();
            if (expirationDate != null && expirationDate.before(DateTimeUtils.getDateNow())) {
                throw new ServiceException(ServiceExpEnums.EXP_EXPIRE_TENANT);
            }
            //进行数据源设置
            Map<String, Object> dataSourceMeta = new HashMap<>();
            dataSourceMeta.put("url", masterTenantDTO.getUrl());
            dataSourceMeta.put("username", masterTenantDTO.getUsername());
            dataSourceMeta.put("password", masterTenantDTO.getPassword());
            dataSourceMeta.put("driverClassName", masterTenantDTO.getDriver());
            dataSource.setTargetDataSources(tenant, dataSource.createDataSource(dataSourceMeta));
            log.info("&&&&&&&&&&& 已设置租户:{} 连接信息: {}", tenant, masterTenantDTO);
        }
        log.info("&&&&&&&&&&& 当前租户:{}", tenant);
        DataSourceHolder.setDb(tenant);
        return true;
    }

    /**
     * 方法执行完之后返回视图前执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        DataSourceHolder.remove();
    }
}
